﻿using System;
using System.Xml;
using System.Linq;
using System.Collections.Generic;
using Infrastructure.Serialization;
using Infrastructure.Diagnostics;

namespace PasswordControl.Core.Data
{
    class PasswordPackage : IPasswordPackage, ISerializable 
    {
        private ICollection<IPasswordItem> m_passwordItems = new List<IPasswordItem>();

        [StoredValue]
        public string PackageId { get; set; }

        public IEnumerable<IPasswordItem> Passwords
        {
            get { return m_passwordItems; }
        }

        public PasswordPackage()
        {
        }

        public PasswordPackage(string id)
        {
            PackageId = id;
        }

        public IPasswordItem AddPasswordItem(string itemName)
        {
            var item = m_passwordItems.SingleOrDefault(i => i.ItemName == itemName);
            if (item == null)
            {
                item = new PasswordItem(itemName);
                m_passwordItems.Add(item);
            }
            return item;
        }

        public bool AddPasswordItem(IPasswordItem item)
        {
            if (m_passwordItems.Any(i => i.ItemName == item.ItemName))
            {
                Logger.Error("Item with same name already exists. name: {0}", item.ItemName);
                return false;
            }
            m_passwordItems.Add(item);
            return true;
        }

        public void RemovePasswordItem(string itemName)
        {
            var item = m_passwordItems.SingleOrDefault(i => i.ItemName == itemName);
            if (item != null) m_passwordItems.Remove(item);
        }

        #region ISerializable

        public void OnSerialize(ISerializer serializer, XmlNode node)
        {
            serializer.SerializeCollection(node, m_passwordItems);
        }

        public void OnDeserialize(ISerializer serializer, XmlNode node)
        {
            serializer.DeserializeNodesOfType<PasswordItem>(node)
                .ToList().ForEach(item => m_passwordItems.Add(item));
        }

        #endregion
    }
}
